
package jrain.fw.http.common.rest.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jrain.fw.core.business.BusinessRequest;
import jrain.fw.core.business.BusinessResponse;
import jrain.fw.core.consts.Consts;
import jrain.fw.core.rest.RestMethod;
import jrain.fw.core.rest.RestService;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.collection.CollectionUtils;
import jrain.utils.lang.LangUtils;
import jrain.utils.lang.StringUtils;

/**
 * <pre>
 * 作者：3244924214@qq.com 
 * 描述：BootstrapAction
 * </pre>
 */
@RestService()
public class BootstrapAction extends BaseAction {

	public BootstrapAction() {
	}

	@RestMethod(name = "/bootstrap/basegrid/*")
	public void rest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		String url = httpRequest.getRequestURI();
		int clength = httpRequest.getContextPath().length();
		url = url.substring(clength);
		List<String> list = CollectionUtils.valueOfList(url, "/");
		if (list.size() == 3 || list.size() == 4) {
			String service = list.get(2);
			String method = list.get(3);
			String version = list.size() == 4 ? "v1" : list.get(4);
			BusinessRequest request = new BusinessRequest(service, method, version);
			String pageNumber = StringUtils.trimNull(httpRequest.getParameter("pageNumber"));
			if(!pageNumber.isEmpty()){
				int pageNum = LangUtils.parseInt(pageNumber);
				if(pageNum>0){
					pageNum = pageNum-1;
				}
				request.putData(Consts.SQL_PAGE, pageNum);
			}
			doAction(request, httpRequest, httpResponse,erequest->{
				String epageNumber = StringUtils.trimNull(erequest.getData("pageNumber"));
				if(!epageNumber.isEmpty()){
					int epageNum = LangUtils.parseInt(epageNumber);
					if(epageNum>0){
						epageNum = epageNum-1;
					}
					request.putData(Consts.SQL_PAGE, epageNum);
				}
			});
		} else {
			write404(httpRequest, httpResponse);
		}
	}
	
	@Override
	protected void writeData(BusinessRequest request, BusinessResponse response, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		Map<String,Object> gridResponse = new HashMap<>();
		gridResponse.put("code", response.getCode());
		gridResponse.put("msg", response.getMsg());
		gridResponse.put("total", response.getTotal());
		gridResponse.put("rows", response.getData());
		gridResponse.put("extData", response.getExtData());
		String data = FwUtils.getJsonService().toPageJson(gridResponse);
		write(request,httpResponse, data);
	}

}
